package pers.qianyu.diytomcat.watcher;

import cn.hutool.core.io.watch.*;
import cn.hutool.log.*;
import pers.qianyu.diytomcat.catalina.*;

import java.nio.file.*;

/**
 * @author mizzle rain
 * @date 2021-01-09 16:54
 */
public class ContextFileChangeWatcher {
    private WatchMonitor watchMonitor;
    private boolean stop = false;

    public ContextFileChangeWatcher(Context context) {
        this.watchMonitor = WatchUtil.createAll(context.getDocBase(), Integer.MAX_VALUE, new Watcher() {
            private void dealWith(WatchEvent<?> event) {
                synchronized (ContextFileChangeWatcher.class) {
                    String fileName = event.context().toString();
                    if (stop) {
                        return;
                    }
                    if (fileName.endsWith(".jar") || fileName.endsWith(".xml") || fileName.endsWith(".class")) {
                        stop = true;
                        LogFactory.get().info(ContextFileChangeWatcher.this + "检测到web应用下重要文件变化：{}", fileName);
                        context.reload();
                    }
                }
            }

            @Override
            public void onCreate(WatchEvent<?> event, Path currentPath) {
                dealWith(event);
            }

            @Override
            public void onModify(WatchEvent<?> event, Path currentPath) {
                dealWith(event);
            }

            @Override
            public void onDelete(WatchEvent<?> event, Path currentPath) {
                dealWith(event);
            }

            @Override
            public void onOverflow(WatchEvent<?> event, Path currentPath) {
                dealWith(event);
            }
        });
        this.watchMonitor.setDaemon(true);
    }

    public void start() {
        watchMonitor.start();
    }

    public void stop() {
        watchMonitor.close();
    }
}
